<?php

function indexBy($list,$indexKey='id',$type='one'){
    $result = [];
    if($type=='one'){
        foreach ($list as $value) {
            $result[$value[$indexKey]] = $value;
        }
    }else{
        foreach ($list as $value) {
            $tmp = $result[$value[$indexKey]]??[];
            $tmp[] = $value;
            $result[$value[$indexKey]] = $tmp;
        }
    }
    return $result;
}


function sendSMS_aliyun($mobile, $TemplateParam = array(['code'=>'123456']),$TemplateCode = 'SMS_154950909',$expired_minites = 5,$type = 'login',$extra = []) {

    $params = array ();

    $dysmsConfig = Yaf_Application::app()->getConfig()['dysms'];
    $accessKeyId = $dysmsConfig->accessKeyId;
    $accessKeySecret = $dysmsConfig->accessKeySecret;

    $params["PhoneNumbers"] = $mobile;

    $params["SignName"] = "阿里云短信测试";

    $params["TemplateCode"] = $TemplateCode;

    $params['TemplateParam'] = $TemplateParam;

    // fixme 可选: 设置发送短信流水号
    $params['OutId'] = "";

    // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
    $params['SmsUpExtendCode'] = "";


    // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
    }

    // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
    $helper = new SignatureHelper();

    // 此处可能会抛出异常，注意catch
    $content = $helper->request(
        $accessKeyId,
        $accessKeySecret,
        "dysmsapi.aliyuncs.com",
        array_merge($params, array(
            "RegionId" => "cn-hangzhou",
            "Action" => "SendSms",
            "Version" => "2017-05-25",
        )),
        true
    );

    $db = Singleton::getDb();
    if(isset($TemplateParam['code'])){
        $extra['code'] = $TemplateParam['code'];
    }   
    $extra['type'] = $type;
    $extra['created_at'] = date('Y-m-d H:i:s');
    $extra['result_code'] = $content->Code;
    $extra['mobile'] = $mobile;
    $extra['content'] = $params["TemplateParam"];
    $extra['expired_at'] = time() + 60*$expired_minites;
    $db->insert('sms_log',$extra);
    return $content->Code == 'OK'; // 'OK'  'InvalidAccessKeyId.NotFound' 'SignatureDoesNotMatch'
}

/**
 * 打印调试函数
 * @param $content
 * @param $is_die
 */
function dd($content, $is_die = true)
{
    header('Content-type: text/html; charset=utf-8');
    echo '<pre>' . print_r($content, true).'</pre>';
    $is_die && die();
}

/**
 * 驼峰命名转下划线命名
 * @param $str
 * @return string
 */
function toUnderScore($str)
{
    $dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
        return '_' . strtolower($matchs[0]);
    }, $str);
    return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
}


/**
 * 写入日志
 * @param string|array $values
 * @param string $dir
 * @return bool|int
 */
function write_log($values, $dir='')
{
    if (is_array($values))
        $values = print_r($values, true);
    // 日志内容
    $cost = intval((microtime(true) - APP_START)*1000).'ms';
    $content = '[' . date('Y-m-d H:i:s') . ']'. $cost . PHP_EOL . $values . PHP_EOL . PHP_EOL;
    try {
        // 文件路径
        $filePath = '../logs/'.$dir;
        // 路径不存在则创建
        !is_dir($filePath) && mkdir($filePath, 0755, true);
        // 写入文件
        return file_put_contents($filePath . date('Ymd') . '.log', $content, FILE_APPEND);
    } catch (\Exception $e) {
        return false;
    }
}

/**
 * curl请求指定url
 * @param $url
 * @param array $data
 * @return mixed
 */
function curl($url, $data = [])
{
    // 处理get数据
    if (!empty($data)) {
        $url = $url . '?' . http_build_query($data);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}
// 微信接口
function curl_post($url, $data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return json_decode($result, true);
}

if (!function_exists('array_column')) {
    /**
     * array_column 兼容低版本php
     * (PHP < 5.5.0)
     * @param $array
     * @param $columnKey
     * @param null $indexKey
     * @return array
     */
    function array_column($array, $columnKey, $indexKey = null)
    {
        $result = array();
        foreach ($array as $subArray) {
            if (is_null($indexKey) && array_key_exists($columnKey, $subArray)) {
                $result[] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
            } elseif (array_key_exists($indexKey, $subArray)) {
                if (is_null($columnKey)) {
                    $index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
                    $result[$index] = $subArray;
                } elseif (array_key_exists($columnKey, $subArray)) {
                    $index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
                    $result[$index] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
                }
            }
        }
        return $result;
    }
}


function sql_logs(){
    $db = Singleton::getDb();
    if($db->logging){
        #write_log($db->info());
        write_log($db->log());
    }    
}

function error_system_log($exception){
    $db = Singleton::getDb();
    $req = new Yaf_Request_http(); 
    $insert = [
        'file'=>$exception->getFile(),
        'line'=>$exception->getLine(),
        'uri' => $req->uri,
        'message' => $exception->getMessage(),
        'created_at' => date('Y-m-d H:i:s'),
        'content'=> json_encode($exception->getTrace())
     ];       
    $db->insert('error_logs',$insert);
}   


function error($msg='error',$code = 422,$data=[]){
    if($code==401){
        header('HTTP/1.1 401 Unauthorized');
    }
    header('Content-type: application/json');
    sql_logs();
    echo json_encode(
        [
            'code'=>$code,
            'message' => $msg,
            'data'=>$data
        ]
    );
    exit();
    return FALSE;
}

function success($data=[],$msg='操作成功'){
	header('Content-type: application/json');
    sql_logs();
	echo json_encode(
		[
			'code'=>200,
			'message' => $msg,
			'data' => $data
		]
	);
    exit();
	return FALSE;
}


/**
 * 多维数组合并
 * @param $array1
 * @param $array2
 * @return array
 */
function array_merge_multiple($array1, $array2)
{
    $merge = $array1 + $array2;
    $data = [];
    foreach ($merge as $key => $val) {
        if (
            isset($array1[$key])
            && is_array($array1[$key])
            && isset($array2[$key])
            && is_array($array2[$key])
        ) {
            $data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
        } else {
            $data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
        }
    }
    return $data;
}

/**
 * 获取全局唯一标识符
 * @param bool $trim
 * @return string
 */
function getGuidV4($trim = true)
{
    // Windows
    if (function_exists('com_create_guid') === true) {
        $charid = com_create_guid();
        return $trim == true ? trim($charid, '{}') : $charid;
    }
    // OSX/Linux
    if (function_exists('openssl_random_pseudo_bytes') === true) {
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
    // Fallback (PHP 4.2+)
    mt_srand((double)microtime() * 10000);
    $charid = strtolower(md5(uniqid(rand(), true)));
    $hyphen = chr(45);                  // "-"
    $lbrace = $trim ? "" : chr(123);    // "{"
    $rbrace = $trim ? "" : chr(125);    // "}"
    $guidv4 = $lbrace .
        substr($charid, 0, 8) . $hyphen .
        substr($charid, 8, 4) . $hyphen .
        substr($charid, 12, 4) . $hyphen .
        substr($charid, 16, 4) . $hyphen .
        substr($charid, 20, 12) .
        $rbrace;
    return $guidv4;
}

function richText($rc)
{
    $rc = preg_replace('/style="[^\"]*"/','',$rc);
    $rc = str_replace('<img','<img style="max-width:100%;height:auto;"',$rc);
    return $rc;
}


function getTreeChildren($list,$parentKey='pid',$parentVal = 0){
    $result = [];
    foreach ($list as $item) {
        if($item[$parentKey] == $parentVal){
            $item['children'] = getTreeChildren($list,$parentKey,$item['id']);
            if(!count($item['children'])){
                unset($item['children']);
            }
            $result[] = $item;
        }
    }
    return $result;
}


/**
 * 循环获取文件
*/
function scan_dir($dir) {
    if ($handle = opendir($dir)) {
        while (false !== ($file = readdir($handle))) {
            if($file=='..' || $file=='.') continue;

            if(is_file($dir.'/'.$file)) {
                $file_list[] = $dir.'/'.$file;
                continue;
            }

            $file_list[$file] = $this->scan_dir($dir.'/'.$file);
            foreach($file_list[$file] as $infile) {
                $file_list[] = $infile;
            }
            unset($file_list[$file]);
        }
        closedir($handle);

        return $file_list;
    }
}
